//
//  UIImageView+MYGVideo.m
//  MYGrow
//
//  Created by 小火科技 on 2024/3/21.
//

#import "UIImageView+MYGVideo.h"
#import <SDWebImage/SDImageCache.h>
#import <AVFoundation/AVFoundation.h>
@implementation UIImageView (MYGVideo)

- (void)videoImageWithvideoURL:(NSURL *)videoURL atTime:(NSTimeInterval)time complete: (void(^)(UIImage * _Nullable image))complete {
    
    //先从缓存中找是否有图片
    SDImageCache *cache =  [SDImageCache sharedImageCache];
    UIImage *memoryImage =  [cache imageFromMemoryCacheForKey:videoURL.absoluteString];
    if (memoryImage) {
        self.image = memoryImage;
        complete(memoryImage);
        return;
    }else{
        UIImage *diskImage =  [cache imageFromDiskCacheForKey:videoURL.absoluteString];
        if (diskImage) {
            self.image = diskImage;
            complete(diskImage);
            return;
        }
    }
    
    if (!time) {
        time = 1;
    }
    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
        
        AVURLAsset *asset = [[AVURLAsset alloc] initWithURL:videoURL options:nil];
        NSParameterAssert(asset);
        AVAssetImageGenerator *assetImageGenerator =[[AVAssetImageGenerator alloc] initWithAsset:asset];
        assetImageGenerator.appliesPreferredTrackTransform = YES;
        assetImageGenerator.apertureMode = AVAssetImageGeneratorApertureModeEncodedPixels;
        CGImageRef thumbnailImageRef = NULL;
        CFTimeInterval thumbnailImageTime = time;
        NSError *thumbnailImageGenerationError = nil;
        thumbnailImageRef = [assetImageGenerator copyCGImageAtTime:CMTimeMake(thumbnailImageTime, 60)actualTime:NULL error:&thumbnailImageGenerationError];
        if(!thumbnailImageRef)
            NSLog(@"thumbnailImageGenerationError %@",thumbnailImageGenerationError);
        UIImage*thumbnailImage = thumbnailImageRef ? [[UIImage alloc]initWithCGImage: thumbnailImageRef] : nil;
        
        dispatch_async(dispatch_get_main_queue(), ^{
            SDImageCache *cache =  [SDImageCache sharedImageCache];
        
            [cache storeImageDataToDisk:UIImagePNGRepresentation(thumbnailImage) forKey:videoURL.path];
            self.image = thumbnailImage;
            complete(thumbnailImage);
        });
        
    });
   
}
@end
